<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        style="width: 190px;"
        class="filter-item"
        placeholder="请输入卡编号"
        v-model="queryForm.cardNo"
      >
      </el-input>
      <el-input
        style="width: 150px;"
        class="filter-item"
        placeholder="请输入领卡人姓名"
        v-model="queryForm.owerName"
      >
      </el-input>
      <el-input
        style="width: 150px;"
        class="filter-item"
        placeholder="请输入领卡人电话"
        v-model="queryForm.owerPhone"
      >
      </el-input>
      <el-input
        style="width: 130px;"
        class="filter-item"
        placeholder="请输入室编号"
        v-model="queryForm.houseId"
      >
      </el-input>
      <el-select
        clearable
        style="width: 135px"
        class="filter-item"
        v-model="queryForm.status"
        placeholder="请选择卡状态"
      >
        <el-option
          v-for="(val, key) in typeOptions"
          :key="key"
          :label="val"
          :value="key"
        >
        </el-option>
      </el-select>
      <el-button
        class="filter-item"
        @click="doQuery"
        type="primary"
        icon="el-icon-search"
        >查询</el-button
      >
      <el-input
        style="width: 150px;"
        class="filter-item"
        placeholder="请输入卡批次"
        v-model="cardBatch"
      >
      </el-input>
      <el-button
        class="filter-item"
        @click="watch"
        type="primary"
        icon="el-icon-warning"
        >激活</el-button
      >
    </div>
    <el-table v-loading="loading" :data="records" style="width: 100%">
      <el-table-column
        prop="batchNo"
        label="卡批次号"
        width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="typeClass"
        label="类型分类"
        width="150"
        align="center"
      >
        <template slot-scope="scope">
          {{ Dicts.TYPE_CLASS[scope.row.typeClass] }}
        </template>
      </el-table-column>
      <el-table-column prop="cardNo" label="卡编号" width="250" align="center">
      </el-table-column>
      <el-table-column
        prop="serialNumber"
        label="卡序列号"
        width="250"
        align="center"
      >
      </el-table-column>
      <el-table-column prop="expdate" label="有效期" width="250" align="center">
      </el-table-column>
      <el-table-column
        prop="owerName"
        label="领卡人姓名"
        width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="owerPhone"
        label="领卡人电话"
        width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column prop="region" label="区域" width="250" align="center">
      </el-table-column>
      <el-table-column prop="address" label="地址" width="250" align="center">
      </el-table-column>
      <el-table-column
        prop="isReceive"
        label="是否领取"
        width="150"
        align="center"
      >
        <template slot-scope="scope">
          {{ Dicts.DOORCARD_IS_RECEIVE[scope.row.isReceive] }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="卡状态" width="150" align="center">
        <template slot-scope="scope">
          {{ Dicts.DOORCARD_STATUS[scope.row.status] }}
        </template>
      </el-table-column>
      <el-table-column
        prop="receiveTime"
        label="领取时间"
        width="250"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="activeTime"
        label="激活时间"
        width="250"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="bindingTime"
        label="绑定时间"
        width="250"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="lostTime"
        label="挂失时间"
        width="250"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="logoutTime"
        label="注销时间"
        width="250"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="modifyTime"
        label="修改时间"
        width="250"
        align="center"
      >
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        class-name="small-padding"
        fixed="right"
        width="300"
      >
        <template slot-scope="scope">
          <el-button
            v-permission="'doorCardHouse:dcWrite'"
            type="primary"
            size="mini"
            v-if="scope.row.status != 3"
            @click="dcWrite(scope.row.cardNo, scope.row.rowId)"
            icon="el-icon-service"
            circle
            title="发卡"
          ></el-button>
          <el-button
            v-permission="'doorCardHouse:receiveCard'"
            size="mini"
            type="success"
            v-if="scope.row.isReceive == 0"
            @click="receiveCard(scope.row.rowId)"
            title="确认领取"
            icon="el-icon-success"
            circle
          ></el-button>
          <el-button
            v-permission="'doorCardHouse:bindHouse'"
            size="mini"
            type="warning"
            @click="openBindHouseDialog(scope.row)"
            title="绑定室"
            icon="el-icon-setting"
            circle
          ></el-button>
          <el-button
            v-permission="'doorCardHouse:out'"
            size="mini"
            type="warning"
            v-if="scope.row.status != 0 && scope.row.status != 3"
            @click="handleLogOut(scope.row.rowId)"
            title="注销"
            icon="el-icon-warning"
            circle
          ></el-button>
          <el-button
            v-permission="'doorCardHouse:active'"
            size="mini"
            type="success"
            v-if="scope.row.status == 0 || scope.row.status == 3"
            @click="activationCard(scope.row.rowId)"
            title="激活"
            icon="el-icon-warning"
            circle
          ></el-button>
          <el-button
            v-permission="'doorCardHouse:delete'"
            size="mini"
            type="danger"
            @click="handleDelete(scope.row.rowId)"
            title="删除"
            icon="el-icon-delete"
            circle
          ></el-button>
          <el-button
            size="mini"
            type="default"
            @click="oplog(scope.row.rowId)"
            title="操作日志"
            icon="el-icon-document"
            circle
          ></el-button>
          <el-button
            size="mini"
            type="primary"
            @click="message(scope.row.rowId)"
            title="持卡人信息"
            icon="el-icon-message"
            circle
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryForm.current"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryForm.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="queryForm.total"
      >
      </el-pagination>
    </div>
    <el-dialog
      :title="`查看门卡操作日志详情`"
      :visible.sync="detailFormVisible"
      width="70%"
    >
      <el-table v-loading="loading" :data="detailRecords" style="width: 100%">
        <el-table-column prop="rowId" label="编号" width="100">
        </el-table-column>
        <el-table-column prop="realName" label="操作人" width="100">
        </el-table-column>
        <el-table-column prop="cardNo" label="卡号" width="200">
        </el-table-column>
        <el-table-column prop="opEvent" label="操作事件" width="100">
          <template slot-scope="scope">
            {{ Dicts.OP_EVENT[scope.row.opEvent] }}
          </template>
        </el-table-column>
        <el-table-column prop="opDesc" label="操作描述" width="150">
        </el-table-column>
        <el-table-column prop="roomName" label="区域" width="400">
        </el-table-column>
        <el-table-column prop="grantUserName" label="授权目标用户" width="150">
        </el-table-column>
        <el-table-column prop="delayBeforeDate" label="延期前日期" width="150">
        </el-table-column>
        <el-table-column prop="delayAfterDate" label="延期后日期" width="150">
        </el-table-column>
        <el-table-column> </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog
      :title="`查看持卡人信息`"
      :visible.sync="messageVisible"
      width="30%"
    >
      <el-form :model="messageForm" style="width: 100%" :ref="messageForm">
        <el-form-item label="卡号:">
          {{ messageForm.cardNo }}
        </el-form-item>
        <el-form-item label="区域:">
          {{ messageForm.region }}
        </el-form-item>
        <el-form-item label="持卡人姓名:">
          {{ messageForm.realName }}
        </el-form-item>
        <el-form-item label="持卡人电话:">
          {{ messageForm.phone }}
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="messageVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="'绑定室信息'"
      :visible.sync="dialogBindHouseFormVisible"
      width="50%"
    >
      <el-form
        :model="bindHouseForm"
        label-width="160px"
        :rules="bindHouseFormRules"
        ref="bindHouseForm"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="卡编号:" prop="cardNo">
              {{ bindHouseForm.cardNo }}
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="区域:" prop="region">
              {{ bindHouseForm.region }}
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="地址:" prop="address">
              {{ bindHouseForm.address }}
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="是否换绑室信息:" prop="switchVal">
              <el-switch
                v-model="bindHouseForm.switchVal"
                active-text="是"
                inactive-text="否"
                @change="changeSwitchVal"
              >
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="20">
            <el-form-item label="绑定区域:" prop="ragion" v-if="isShow">
              <el-select
                filterable
                v-model="bindHouseForm.provinceId"
                placeholder="请选择省份"
                style="width: 32%;"
                @change="provChange"
              >
                <el-option
                  v-for="(item, index) in provinces"
                  :key="index"
                  :value="item.rowId"
                  :label="item.cnName"
                ></el-option>
              </el-select>
              <el-select
                filterable
                v-model="bindHouseForm.cityId"
                placeholder="请选择城市"
                style="width: 32%;"
                @change="cityChange"
              >
                <el-option
                  v-for="(item, index) in citys"
                  :key="index"
                  :value="item.rowId"
                  :label="item.cnName"
                ></el-option>
              </el-select>
              <el-select
                filterable
                v-model="bindHouseForm.districtId"
                placeholder="请选择区县"
                style="width: 32%;"
                @change="distChange"
              >
                <el-option
                  v-for="(item, index) in districts"
                  :key="index"
                  :value="item.rowId"
                  :label="item.cnName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="20">
            <el-form-item label="绑定地址:" prop="communityId" v-if="isShow">
              <el-select
                filterable
                v-model="bindHouseForm.communityId"
                placeholder="请选择小区"
                style="width: 24%;"
                @change="commChange"
              >
                <el-option
                  v-for="(item, index) in communitys"
                  :key="index"
                  :value="item.rowId"
                  :label="item.name"
                ></el-option>
              </el-select>
              <el-select
                filterable
                v-model="bindHouseForm.buildingId"
                placeholder="请选择楼栋"
                style="width: 24%;"
                @change="buildChange"
              >
                <el-option
                  v-for="(item, index) in buildings"
                  :key="index"
                  :value="item.rowId"
                  :label="item.name"
                ></el-option>
              </el-select>
              <el-select
                filterable
                v-model="bindHouseForm.unitId"
                placeholder="请选择单元"
                style="width: 24%;"
                @change="unitChange"
              >
                <el-option
                  v-for="(item, index) in units"
                  :key="index"
                  :value="item.rowId"
                  :label="item.name"
                ></el-option>
              </el-select>
              <el-select
                filterable
                v-model="bindHouseForm.houseId"
                placeholder="请选择室"
                style="width: 24%;"
                @change="houseChange"
              >
                <el-option
                  v-for="(item, index) in houses"
                  :key="index"
                  :value="item.rowId"
                  :label="item.number"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogBindHouseFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="execBindHouseForm" v-if="isShow"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryDoorCardHouse,
  deleteDoorCard,
  cancelDoorCard,
  activationDoorCard,
  receiveCard,
  bindHouse,
  volumeActiveDoorCard,
  selectDoorCardOplog,
  selectUserMessageByDoorCard
} from '@/api/card'
import { queryProvince, getCity, getDistrict } from '@/api/area'
import {
  selectAllCommunity,
  selectByCommunityIdBuilding,
  selectByBuildingUnit,
  selectAllHouse,
  editDoorCard
} from '@/api/community'
export default {
  name: 'doorCardHouse',
  data() {
    return {
      messageVisible: false,
      messageForm: [],
      detailFormVisible: false,
      detailRecords: [],
      cardBatch: '',
      dialogBindHouseFormVisible: false,
      loading: false,
      queryForm: {
        current: 1,
        pages: 0,
        total: 0,
        size: 10,
        status: undefined,
        title: undefined
      },
      bindHouseForm: {},
      bindHouseFormRules: {},
      isShow: false,
      typeOptions: Dicts.DOORCARD_STATUS,
      provinces: [],
      citys: [],
      districts: [],
      communitys: [],
      buildings: [],
      units: [],
      houses: [],
      records: [],
      exampleForm: []
    }
  },
  created() {
    this.doQuery()
    this.readerd8().then(d8 => {
      this.reader = d8
    })
  },
  methods: {
    handleCurrentChange(current) {
      this.queryForm.current = current
      this.doQuery()
    },
    handleSizeChange(size) {
      this.queryForm.size = size
      this.doQuery()
    },
    doQuery() {
      this.loading = true
      queryDoorCardHouse(this.queryForm).then(({ data: { data } }) => {
        this.queryForm.current = data.current
        this.queryForm.pages = data.pages
        this.queryForm.total = data.total
        this.queryForm.size = data.size
        this.records = data.records
        this.loading = false
      })
    },
    oplog(rowId) {
      this.exampleForm.doorCardId = rowId
      selectDoorCardOplog(this.exampleForm).then(
        ({ data: { code, data, msg } }) => {
          this.detailFormVisible = true
          this.detailRecords = data
          this.loading = false
        }
      )
    },
    message(rowId) {
      this.messageVisible = true
      selectUserMessageByDoorCard(rowId).then(({ data: { code, data } }) => {
        this.messageForm = {}
        if (data === null || data === undefined) {
          this.messageForm = []
        } else {
          this.messageForm = data
        }
      })
    },
    watch() {
      this.$confirm('此操作将批量激活该批次的所有门禁卡, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        volumeActiveDoorCard(this.cardBatch).then(({ data: { data, msg } }) => {
          this.doQuery()
          this.$message({
            showClose: true,
            message: '该批次下的卡片激活成功',
            type: 'success'
          })
        })
      })
    },
    handleDelete(rowId) {
      this.$confirm('此操作将删除该门禁卡, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDoorCard(rowId).then(({ data: { data, msg } }) => {
          this.doQuery()
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
      })
    },
    handleLogOut(rowId) {
      this.$confirm('此操作将注销该门禁卡, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelDoorCard(rowId).then(({ data: { data, msg } }) => {
          this.doQuery()
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
      })
    },
    activationCard(rowId) {
      this.$confirm('此操作将激活该门禁卡, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        activationDoorCard(rowId).then(({ data: { data, msg } }) => {
          this.doQuery()
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
      })
    },
    dcWrite(cardNo, rowId) {
      let ret
      let serialNumber
      // 调用控件对象dc_init方法，初始化端口
      ret = this.reader.dc_init(100, 115200)
      // 成功则返回串口标识符>0，失败返回负值，见错误代码表
      if (ret < 0) {
        alert('初始化失败！')
        return
      } else if (ret > 0) {
        // 发卡
        ret = this.reader.dc_card_double(0) // 0为单卡操作模式
        serialNumber = this.reader.get_bstrRBuffer_asc
        if (ret !== 0) {
          alert('未发现卡片！')
          this.reader.dc_beep(10)
          this.reader.dc_exit()
          return
        } else {
          // 密钥加载及认证
          this.reader.put_bstrSBuffer_asc = 'FDB0916AC12FFF07806977681FE2ABC9'
          this.reader.dc_load_key(0, 13)
          ret = this.reader.dc_authentication(0, 13)
          if (ret !== 0) {
            alert('认证失败')
            this.reader.put_bstrSBuffer_asc = 'FFFFFFFFFFFFFF078069FFFFFFFFFFFF' // 还原设备认证key
            this.reader.dc_load_key(0, 13)
            this.reader.dc_beep(10)
            this.reader.dc_exit()
            return
          } else {
            this.reader.put_bstrSBuffer_asc = cardNo + '000000000000'
            ret = this.reader.dc_write(52)
            if (ret !== 0) {
              this.reader.dc_beep(10)
              this.reader.put_bstrSBuffer_asc =
                'FFFFFFFFFFFFFF078069FFFFFFFFFFFF' // 还原设备认证key
              this.reader.dc_load_key(0, 13)
              this.reader.dc_exit()
              alert('写入失败！')
              return
            } else {
              this.reader.put_bstrSBuffer_asc =
                'FFFFFFFFFFFFFF078069FFFFFFFFFFFF' // 还原设备认证key
              this.reader.dc_load_key(0, 13)
              this.reader.dc_beep(100)
              this.reader.dc_exit()
              editDoorCard(rowId, serialNumber).then(
                ({ data: { data, msg } }) => {
                  this.$message({
                    showClose: true,
                    message: '发卡成功！',
                    type: 'success'
                  })
                }
              )
            }
          }
        }
      }
    },
    receiveCard(rowId) {
      this.$confirm('是否确认已领取该门禁卡?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        receiveCard(rowId).then(({ data: { data, msg } }) => {
          this.doQuery()
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
      })
    },
    openBindHouseDialog(row) {
      this.isShow = false
      queryProvince().then(({ data: { data } }) => {
        this.provinces = data
        this.bindHouseForm = {
          doorCardId: row.rowId,
          cardNo: row.cardNo,
          region: row.region,
          address: row.address,
          switchVal: false
        }
        this.dialogBindHouseFormVisible = true
        this.$refs.bindHouseForm && this.$refs.bindHouseForm.resetFields()
      })
    },
    changeSwitchVal() {
      this.bindHouseForm.switchVal === true
        ? (this.isShow = true)
        : (this.isShow = false)
    },
    provChange() {
      getCity(this.bindHouseForm.provinceId).then(({ data: { data } }) => {
        this.citys = []
        this.districts = []
        this.communitys = []
        this.buildings = []
        this.units = []
        this.houses = []
        this.citys = data
        this.bindHouseForm.cityId = ''
        this.bindHouseForm.districtId = ''
        this.bindHouseForm.communityId = ''
        this.bindHouseForm.buildingId = ''
        this.bindHouseForm.unitId = ''
        this.bindHouseForm.houseId = ''
      })
    },
    cityChange() {
      getDistrict(this.bindHouseForm.cityId).then(({ data: { data } }) => {
        this.districts = []
        this.communitys = []
        this.buildings = []
        this.units = []
        this.houses = []
        this.districts = data
        this.bindHouseForm.districtId = ''
        this.bindHouseForm.communityId = ''
        this.bindHouseForm.buildingId = ''
        this.bindHouseForm.unitId = ''
        this.bindHouseForm.houseId = ''
      })
    },
    distChange() {
      selectAllCommunity(this.bindHouseForm.districtId).then(
        ({ data: { data } }) => {
          this.communitys = []
          this.buildings = []
          this.units = []
          this.houses = []
          this.communitys = data
          this.bindHouseForm.communityId = ''
          this.bindHouseForm.buildingId = ''
          this.bindHouseForm.unitId = ''
          this.bindHouseForm.houseId = ''
        }
      )
    },
    commChange() {
      selectByCommunityIdBuilding(this.bindHouseForm.communityId).then(
        ({ data: { data } }) => {
          this.buildings = []
          this.units = []
          this.houses = []
          this.buildings = data
          this.bindHouseForm.buildingId = ''
          this.bindHouseForm.unitId = ''
          this.bindHouseForm.houseId = ''
        }
      )
    },
    buildChange() {
      selectByBuildingUnit(this.bindHouseForm.buildingId).then(
        ({ data: { data } }) => {
          this.units = []
          this.houses = []
          this.units = data
          this.bindHouseForm.unitId = ''
          this.bindHouseForm.houseId = ''
        }
      )
    },
    unitChange() {
      selectAllHouse(this.bindHouseForm.unitId).then(({ data: { data } }) => {
        this.houses = data
        this.bindHouseForm.houseId = ''
      })
    },
    houseChange() {
      queryProvince().then(({ data: { data } }) => {
        this.provinces = data
      })
    },
    execBindHouseForm() {
      if (
        this.bindHouseForm.houseId === undefined ||
        this.bindHouseForm.houseId === ''
      ) {
        this.$message({
          showClose: true,
          message: '请选择绑定区域和地址',
          type: 'warning'
        })
      } else {
        bindHouse(this.bindHouseForm).then(({ data: { code, data } }) => {
          if (code === 0) {
            this.doQuery()
            this.dialogBindHouseFormVisible = false
          }
          this.$message({
            showClose: true,
            message: code === 0 ? '绑定成功' : '绑定失败',
            type: code === 0 ? 'success' : 'error'
          })
        })
      }
    }
  },
  components: {}
}
</script>

<style scoped></style>
<style>
.el-transfer-panel {
  width: 40% !important;
}
</style>
